package com.halflife.framework.participant.range;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.halflife.framework.participant.range.service.RangeService;
import com.halflife.framework.participant.user.UserView;
import com.halflife.framework.participant.user.UserViewRepository;
import com.halflife.framework.converter.MapHandler;
import com.halflife.framework.domain.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class RoleMembershipAdminController {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private RoleMembershipRepository roleMembershipRepository;
    @Resource
    private RangeService rangeService;
    @Resource
    private UserViewRepository userViewRepository;

    @RequestMapping("/roleMembership/list")
    public String gotoList(@RequestParam(required = false) HashMap<String,Object> queryParam,
                           Page page, HttpServletResponse response, HttpServletRequest request,
                           Model model, Integer roleId) {
        MapHandler.handleMap(queryParam);
        if (page == null) {
            page = new Page();
        }
        page.setQueryParam(queryParam);
        //加入角色过滤
        queryParam.put("valid", true);
        queryParam.put("roleId", roleId);
        int totalCount = roleMembershipRepository.selectCount(queryParam);
        List<RoleMembership> list = roleMembershipRepository.selectListByPage(queryParam);
        page.setTotalCount(totalCount);
        page.setMode(model);
        model.addAttribute("list",list);
        model.addAttribute("roleId",roleId);
        model.addAttribute("queryParam",queryParam);
        return "roleMembership/list";
    }

    @RequestMapping("/roleMembership/operate")
    public String gotoOperate(Integer id,HttpServletResponse response,
                               HttpServletRequest request, Model model) {
        RoleMembership roleMembership = new RoleMembership();
        if(id!=null){
            roleMembership = roleMembershipRepository.selectByPrimaryKey(id);
        }
        model.addAttribute("roleMembership",roleMembership);
        return "roleMembership/operate";
    }

    @PostMapping("/roleMembership/save")
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity save(RoleMembership roleMembership, HttpServletRequest request,
                              HttpServletResponse response, Model model) {
        try {
            if(roleMembership.getId()!=null){
                roleMembershipRepository.updateByPrimaryKey(roleMembership);
            }else {
                roleMembership.init();
                Integer a = roleMembershipRepository.insert(roleMembership);
            }
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }

    @DeleteMapping("/roleMembership/delete")
    public ResponseEntity setRiderState(Integer id, Integer state) {
        try {
            RoleMembership roleMembership = new RoleMembership();
            roleMembership.setId(id);
            roleMembership.setValid(Boolean.FALSE);
            roleMembershipRepository.updateByPrimaryKeySelective(roleMembership);
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }

    /**
     * 跳转选择角色人员页面
     * @param queryParam
     * @param page
     * @param response
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/roleMembership/rangeSetList")
    public String RoleMembershipSetList(@RequestParam(required = false) HashMap<String,Object> queryParam,
                                        Page page, HttpServletResponse response, HttpServletRequest request,
                                        Model model, Integer roleId, Integer operType) {
        try{
            //operType 0-教师 1-学生 2-教职工 3-管理员
            model.addAttribute("data", rangeService.getJsonByOper(roleId, operType));
            model.addAttribute("roleId", roleId);
        }catch (Exception e){

            System.out.println(e.getMessage());
            e.printStackTrace();
            log.info(e.getMessage());
        }

        return "roleMembership/roleMembershipSetList";
    }

    /**
     *  生成角色权限
     */
    @PostMapping("/roleMembership/saveRoleMembershipByUserViewIds")
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity saveRoleMembershipByUserViewIds(HttpServletRequest request,
                                                      HttpServletResponse response, Model model,
                                                      String ids, String roleId) {
        try {

            //删除原权限
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("valid", true);
            paramMap.put("roleId", Integer.valueOf(roleId));
            List<RoleMembership> roleMemberships = roleMembershipRepository.selectAll(paramMap);
            if(roleMemberships.size() > 0){

                for(RoleMembership roleMembership: roleMemberships){

                    roleMembershipRepository.deleteByPrimaryKey(roleMembership.getId());
                }
            }
            if(ids != null){

                String[] ids_ = ids.split(",");
                if(ids_.length > 0){

                    for(String userViewId : ids_){

                        UserView userView = userViewRepository.selectByPrimaryKey(Integer.valueOf(userViewId));
                        if(userView!=null){

                            RoleMembership rr = new RoleMembership();
                            rr.init();
                            rr.setUserViewId(Integer.valueOf(userView.getId()));
                            rr.setRoleId(Integer.valueOf(roleId));
                            roleMembershipRepository.insert(rr);
                        }
                    }
                }
            }

        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }
}
